from django.shortcuts import render
from io import BytesIO
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse, HttpResponseRedirect
from django.http import JsonResponse

from .code import create_validate_code
from .interface import Iden
from .models import Teacher, Administrator, Student, Class, personalReport
from Completion.models import Completion
from ShortAnswer.models import ShortAnswer
from models import operate_log


def login(request):
    return render(request, 'signin.html')


@csrf_exempt
def logout(request):
    request.session.flush()
    return HttpResponseRedirect('/')


@csrf_exempt
def show_code(request):
    f = BytesIO()
    '''
        验证码第一个参数是字体 故使用自己系统可用的字体 放入/static 的 font 文件里  默认空，为windows字体'''
    # img, code = create_validate_code('DejaVuSans.ttf')
    img, code = create_validate_code()  # 返回的是元组   参数为 当前系统所接受的字体 在 /static 文件夹内
    # img, code = create_validate_code('NotoSerifCJK-Bold.ttc')

    img.save(f, 'PNG')  # 生成验证码
    request.session['CheckCode'] = code  # 相当于在每次code 的session过期之前替换session中的值
    return HttpResponse(f.getvalue())


@csrf_exempt
def operate_login(request):  # 登录
    iden = Iden()
    res = {}  # 返回信息字典1
    if request.method == 'POST':
        code = request.POST.get('code')
        check_code = request.session['CheckCode']
        iden.iden = request.POST.get('person')
        iden.id = request.POST.get('userid')
        if code.lower() != check_code.lower():  # 对比验证码
            res['status'] = 103
            return JsonResponse(res)
        sql = iden.iden_file()
        if sql is None or sql == 203:  # 账号是否存在
            res['status'] = 203
            return JsonResponse(res)
        else:
            pwd1 = request.POST.get('password')
            if iden.iden == 'teacher':
                pwd2 = sql.Psw
            elif iden.iden == 'student':
                pwd2 = sql.Psw
            else:
                pwd2 = sql.Psw
            info = iden.match_pwd(pwd1, pwd2)  # 密码验证
            if info:
                request.session['account'] = iden.id
                request.session['iden'] = iden.iden  # session设置身份iden
                iden.one_point_login(request)  # 验证单个登录
                request.session.set_expiry(3600)
                if iden.iden == 'teacher':
                    request.session['name'] = sql.Name
                    request.session['gender'] = sql.Gender
                    res['status'] = 200
                elif iden.iden == 'student':
                    request.session['name'] = sql.Name
                    request.session['gender'] = sql.Gender
                    res['status'] = 201
                else:
                    request.session['name'] = sql.Name
                    res['status'] = 202
                del request.session['CheckCode']
                return JsonResponse(res)
            else:
                res['status'] = 100
                return JsonResponse(res)
    else:
        res['status'] = 403
        return JsonResponse(res)

@csrf_exempt
def register(request):
    return render(request, 'pages-signup.html')


@csrf_exempt
def operate_register(request):  # 注册
    iden = Iden()
    res = {}
    if request.method == 'POST':
        iden.iden = request.POST.get('person')
        iden.id = request.POST.get('userid')
        name = request.POST.get('username')
        pwd1 = request.POST.get('password1')
        if iden.iden == 'teacher':
            sql = iden.iden_file()
            if sql != 203 and sql is not None:  # 账号存在
                res['status'] = 203
                return JsonResponse(res)
            else:
                operate_log.add(request, "新增" + name + "老师", "添加")
                sql = Teacher(Account=iden.id, Name=name, Email=iden.id + '@qq.com', Psw=pwd1)
                sql.save()
                res['status'] = 200
            return JsonResponse(res)
        elif iden.iden == 'student':
            ema = request.POST.get('email')
            code = request.POST.get('code')
            check_code = request.session['CheckCode']
            if code.lower() != check_code.lower():  # 对比验证码
                res['status'] = 103
                return JsonResponse(res)
            sql = iden.iden_file()
            if sql != 203 and sql is not None:  # 账号存在
                res['status'] = 203
                return JsonResponse(res)
            else:
                pwd2 = request.POST.get('password2')
                info = iden.match_pwd(pwd1, pwd2)
                if info != True:
                    res['status'] = 100
                    return JsonResponse(res)
                else:
                    sql = Student(Account=iden.id, Name=name, Email=ema, Psw=pwd1)
                    stuReport = personalReport(stu_account=iden.id, choiceRight=0, choiceWrong=0,
                                               completionRight=0, completionWrong=0,
                                               shortAnswerRight=0, shortAnswerWrong=0)
                    sql.save()
                    stuReport.save()
                    res['status'] = 200
                    return JsonResponse(res)
        elif iden.iden == 'manager':
            sql = iden.iden_file()
            if sql != 203 and sql is not None:  # 账号存在
                res['status'] = 203
                return JsonResponse(res)
            operate_log.add(request, "新增" + name + "管理员", "添加")
            sql = Administrator(Account=iden.id, Name=name, Psw=pwd1)
            sql.save()
            res['status'] = 200
            return JsonResponse(res)
    else:
        res['status'] = 403
        return JsonResponse(res)


@csrf_exempt
def modify(request):
    res = {}
    if request.method == 'POST':
        account = request.session.get('account')
        iden = request.session.get('iden')
        name = request.POST.get('name')
        motto = request.POST.get('motto')
        sex = request.POST.get('sex')
        age = request.POST.get('age')
        email = request.POST.get('email')
        if iden == 'teacher':
            passWord = Teacher.objects.filter(Account=account).values()[0].get('Psw')
            sql = Teacher(Account=account, Name=name, Psw=passWord, Motto=motto, Gender=sex, Age=age, Email=email)
            request.session['gender'] = sql.Gender
            sql.save()
            res['status'] = 200
            return JsonResponse(res)
        elif iden == 'student':
            passWord = Student.objects.filter(Account=account).values()[0].get('Psw')
            sql = Student(Account=account, Name=name, Psw=passWord, Motto=motto, Gender=sex, Age=age, Email=email)
            request.session['gender'] = sql.Gender
            sql.save()
            res['status'] = 200
            return JsonResponse(res)
        else:
            res['status'] = 403
            return JsonResponse(res)
    else:
        res['status'] = 403
        return JsonResponse(res)

@csrf_exempt
def myHome(request):
    account = request.session.get('account')
    iden = request.session.get('iden')
    if iden == 'teacher':
        person = Teacher.objects.get(Account=account)
        shortAnswerTotal = ShortAnswer.objects.all().count()
        completionTotal = Completion.objects.all().count()
        try:
            classInfo = Class.objects.get(tch_account=account)
        except:
            classInfo = ''
        if classInfo != '':
            if completionTotal and classInfo.totalCompletionRight:
                comRate = classInfo.totalCompletionRight / completionTotal * 100
                comRate = round(comRate, 2)
            else:
                comRate = ''
        else:
            comRate = ''
        if classInfo != '':
            if shortAnswerTotal and classInfo.totalCompletionRight:
                shortRate = classInfo.totalShortAnswerRight / shortAnswerTotal * 100
                shortRate = round(shortRate, 2)
            else:
                shortRate = ''
        else:
            shortRate = ''
        try:
            studentInfo = Student.objects.filter(Class=account)
        except:
            studentInfo = None
        return render(request, 'pages-profile.html',
                      {'person': person, 'Class': classInfo, 'student': studentInfo, 'comTotal': completionTotal,
                       'shortTotal': shortAnswerTotal, 'comRate': comRate, 'shortRate': shortRate})
        # except:
        #     return render(request, 'pages-profile.html', {'person': person, 'comTotal': completionTotal, 'shortTotal': shortAnswerTotal})
    elif iden == 'student':
        person = Student.objects.get(Account=account)
        shortAnswerTotal = ShortAnswer.objects.all().count()
        completionTotal = Completion.objects.all().count()
        try:
            personInfo = personalReport.objects.get(stu_account=account)
            completionRight = personInfo.completionRight
            shortAnswerRight = personInfo.shortAnswerRight
            completionWrong = personInfo.shortAnswerWrong
            shortAnswerWrong = personInfo.shortAnswerWrong
        except:
            personInfo = None
            completionRight = 0
            shortAnswerRight = 0

        self_class = Student.objects.filter(Account=account).values()[0]
        classnum = self_class.get('Class')
        try:
            classInfo = Class.objects.get(tch_account=classnum)
        except Class.DoesNotExist:
            classInfo = None
        if completionTotal and completionRight:
            comRate = completionRight / completionTotal * 100
            comRate = round(comRate, 2)
        else:
            comRate = ""
        if shortAnswerTotal and shortAnswerRight:
            shortRate = shortAnswerRight / shortAnswerTotal * 100
            shortRate = round(shortRate, 2)
        else:
            shortRate = ""
        if shortAnswerTotal and completionTotal:
            totalRate = 100 * (completionRight + shortAnswerRight) / (shortAnswerTotal + completionTotal)
            totalRate = round(totalRate, 2)
        else:
            totalRate = ""
        try:
            studentInfo = Student.objects.filter(Class=account)
        except:
            studentInfo = None
        return render(request, 'stu_profile.html', {'person': person, 'student': studentInfo, 'totalRate': totalRate,
                                                    'shortAnswer': shortAnswerRight, 'Class': classInfo,
                                                    'comRate': comRate, 'shortRate': shortRate,
                                                    'shortAnswerRight': shortAnswerRight,
                                                    'completionRight': completionRight,
                                                    'shortAnswerTotal': shortAnswerTotal,
                                                    'completionTotal': completionTotal,
                                                    'completionWrong': completionWrong,
                                                    'shortAnswerWrong':shortAnswerWrong})
    else:
        person = Administrator.objects.get(Account=account)
        return render(request, 'AccountManage.html', {'person': person})


@csrf_exempt
def tch_createClass(request):
    res = {}
    if request.method == 'POST':
        className = request.POST.get('className')
        account = request.session['account']
        if Class.objects.filter(tch_account=account):
            res['status'] = 201
            return JsonResponse(res)
        else:
            sql = Class(tch_account=account, className=className, peopleNum=0)
            name = Teacher.objects.get(Account=account).Name
            sex = Teacher.objects.get(Account=account).Gender
            age = Teacher.objects.get(Account=account).Age
            psw = Teacher.objects.get(Account=account).Psw
            email = Teacher.objects.get(Account=account).Email
            motto = Teacher.objects.get(Account=account).Motto
            pic = Teacher.objects.get(Account=account).Pic
            tch_sql = Teacher(Name=name, Age=age, Gender=sex, Psw=psw, Account=account, Email=email, Motto=motto, Pic=pic, Class=account)
            sql.save()
            tch_sql.save()
            res['status'] = 200
            return JsonResponse(res)
    else:
        res['status'] = 403
        return JsonResponse(res)

@csrf_exempt
def tch_deleteClass(request):
    res = {}
    if request.method == 'POST':
        account = request.session['account']
        try:
            sql = Class.objects.get(tch_account=account)
            students = list(Student.objects.filter(Class=account))
            for stu in students:
                stuSql = Student(Name=stu.Name, Gender=stu.Gender, Account=stu.Account, Psw=stu.Psw, Email=stu.Email, Motto=stu.Motto, Class=None)
                stuSql.save()
            sql.delete()
            res['status'] = 200
        except:
            res['status'] = 500
        return JsonResponse(res)
    else:
        res['status'] = 403
        return JsonResponse(res)
